/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
import React, { Component } from 'react';
import { Table, Button, Form, Tabs, Modal ,Select} from 'antd';
import '@/assets/css/settings';
import * as Utils from '../../../utils_yyr/action';
import BasicDrawer from '../../../components_yyr/common/basicDrawer';
import Paging from '../../../components_yyr/commponent/Paging';
import BasicConfirm from '../../../components_yyr/common/basicConfirm';
import { euqApplicationName } from '../../../config';

const { TabPane } = Tabs;
const { Option } = Select;

class TeamGroups extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [], //数据源
		drawerVisible: false, //新增修改抽屉的显示与隐藏
		chooseData: {}, //用checkbox选择好的数据
		drawerTitle: '', //抽屉的标题
		total: 0, //总数据量
		formValues: {},
		//选中值得组合
		selectedData: [],
		selectedKeys: [],
		//选中班组的类型集合
		typeList: [false, false, false],
		handleType:0,
		list: [
			{ id:1, name: '维修'},
			{  id:2, name: '保养'},
			{  id:3, name: '巡检'}
		],
		visibleDispatch:false,
		userList:[],
		chooseDataUser:[],
		record:{},
		defaultUser:[],
	};
	componentDidMount() {
		this.fetch({
			pageNum: 1,
			pageSize: 10
		});
		// this.getInfo();
	}
	//初始化加载数据
	fetch = data => {
		let str = ''
		for(var key in data){
			if(data[key]){
				str += `&${key}=${data[key]}`
			}
		}
		this.setState({ loading: true })
		 this.get(euqApplicationName + '/parameter_setting_public/queryTeamPageList?'+str).then(res => {
		 	this.setState({
				loading: false,
		 		dataSource: res.data,
		 		total:res.total,
				formValues:data
		 	});
		 })
	};

	//表单查询
	filterSubmit = values => {
		values.pageNum = this.state.formValues.pageNum;
		values.pageSize = this.state.formValues.pageSize;
		this.fetch(values);
	};

	handleConfirm = (value, api, chooseData) => {
		// let newDataSource = [];
		// for (let i of this.state.dataSource) {
		// 	let flag = true;
		// 	for (let j of chooseData) {
		// 		if (j.key == i.key) {
		// 			flag = false;
		// 			break;
		// 		}
		// 	}
		// 	if (flag) {
		// 		newDataSource.push(i);
		// 	}
		// }
		// this.setState({
		// 	dataSource: newDataSource,
		// 	selectedKeys: [],
		// 	selectedData: []
		// });

		//暂时注释
		// if (api === 1) {
			console.log(this.state.selectedData)
		 let str = ''
		 for(var item of this.state.selectedData){
			 str += item.id + ','
		 }
		this.get(`${euqApplicationName}/parameter_setting_public/deleteTeam?ids=${str.slice(0, str.length - 1)}`).then(res => {
				this.success();
				this.fetch({ ...this.state.formValues });
				this.setState({selectedKeys:[],selectedData:[]})
			});
		// }
	};

	//头部关键字查询部分
	formList = () => {
		const formList = [{ type: 'INPUT', label: '单位名称、单位编码、联系人', field: 'factoryName', col: 14 }];
		return formList;
	};

	//判断选中班组的类型
	checkTeamType = type => {
		const typeList = [false,false,false];
		if (typeof type == 'undefined') {
			return typeList;
		}
		let tempList = type.split(',');
		console.log(tempList)
		if (tempList.includes('维修')) {
			typeList[0] = true;
		}
		if (tempList.includes('保养')) {
			typeList[1] = true;
		}
		if (tempList.includes('巡检')) {
			typeList[2] = true;
		}
		return typeList;
	};

	//抽屉中信息列表
	drawerFormList = data => {
		let teamtype = []
		for(var key in this.state.typeList){
			if(this.state.typeList[key]){
				teamtype.push(Number(key)+1)
			}
		}
		const drawerFormList = [
			{ type: 'INPUT', label: '维修班组', field: 'name', initialValue: data.name, required: true  },
			{ type: 'INPUT', label: '班组编码', field: 'code', initialValue: data.code, required: true },
			{
				type: 'CHECKBOX',
				label: '类型',
				field: 'type',
				initialValue: teamtype,
				required: true,
				list: [
					{ id:1, name: '维修'},
					{  id:2, name: '保养'},
					{  id:3, name: '巡检' }
				],name: 'name', valueField: 'id',
			}
		];
		return drawerFormList;
	};

	// 提交modal
	handleSubmit = data => {
		const { list} = this.state;
		//暂时注释
		const id = this.state.chooseData && this.state.chooseData.id;
		if (id&&this.state.handleType===1) {
			data = Object.assign({}, data, { id: id });
			data.updateId = localStorage.getItem('userId');
		} else {
			data.createId = localStorage.getItem('userId');
		}
		let str = ''
		if(data.type && data.type.length>0){
			for(var itemss of list){
				for(var item of data.type){
					if(itemss.id === item){
						str += itemss['name'] + ','
					}
				}
			}
			
		}
		data.type = str.slice(0,str.length-1)
		console.log(data)
		this.post(euqApplicationName + '/parameter_setting_public/addTeam', { data:[data] }).then(res => {
			this.success();
			this.fetch({ ...this.state.formValues });
			this.onClose();
			this.setState({selectedKeys:[],selectedData:[]})
		});
	};

	// 打开modal，判断是修改还是新增 0新增 1修改
	handleModal = (type, data) => {
		const { selectedData } = this.state;
		if (type) {
			if (selectedData.length == 1) {
				this.setState({
					drawerTitle: '修改',
					drawerVisible: true,
					chooseData: selectedData[0],
					typeList: this.checkTeamType(selectedData[0].type),
					handleType:type
				});
			} else {
				Utils.openNotification('warning', '请只选择一条修改');
			}
		} else {
			this.setState({
				drawerTitle: '添加',
				typeList: [false, false, false],
				drawerVisible: true,
				handleType:type,
			});
		}
	};

	onClose = () => {
		this.setState({
			drawerVisible: false,
			chooseData: {},selectedKeys:[],selectedData:[],
			typeList: [false, false, false]
		});
		this.modalRef.props.form.resetFields();
	};

	showModal = (record) => {
		this.get(euqApplicationName + '/parameter_setting_public/queryUserInfoList').then(res => {
			var defaultUser = []
			if(record.userIdList){
				console.log(record.userIdList)
				for(var ote of record.userIdList){
					defaultUser.push(ote.userId)
				}
			}
			console.log(defaultUser)
			this.setState({
				defaultUser,
				userList : res,
				record
			});
			setTimeout(() => {
				this.setState({visibleDispatch:true,})
			}, 55);
		})
	}
	onChangeModal = (checkedValues) =>{
		this.setState({chooseDataUser:checkedValues})
	}
	handleOk = () => {
		this.props.form.validateFields(['chooseDataUser'],(err,value)=>{
			if(!err){
				this.post(euqApplicationName + '/parameter_setting_public/addTeamUserList',{data:{teamId:this.state.record.id,userIdList:value['chooseDataUser']}}).then(res => {
					this.success()
					this.fetch({...this.state.formValues})
					this.handleCancel()
				})
			}
		})
		
	}
	handleCancel = () => {
		this.setState({visibleDispatch:false,userIdList:[],defaultUser:[]})
		this.props.form.resetFields(['chooseDataUser'])
		this.forceUpdate()
	}
	render() {
		const columns = [
			// { title: '序号', width: 100, dataIndex: 'id' },
			{ title: '维修班组', width: 100, dataIndex: 'name' },
			{ title: '班组编码', width: 150, dataIndex: 'code' },
			{ title: '类型', width: 150, dataIndex: 'type' },
			{ title: '班组人员', width: 150, render:(record)=>{
				let str = ''
				for(var item of record.userIdList){
					str += item.userName + ','
				}
				return str.slice(0, str.length - 1)
			}},
			{
				title: '操作', width: 80, 
				render: (text, record) => {
					return <span><a href onClick={() => this.showModal(record)}>绑定人员</a></span>
				}
			},
		];

		const { chooseData, drawerVisible, drawerTitle, dataSource, loading, total, formValues, selectedKeys, selectedData,userList } = this.state;

		const drawerProps = {
			onRef: ref => (this.modalRef = ref),
			visible: drawerVisible,
			width: 700,
			drawerFormList: this.drawerFormList(chooseData),
			submit: this.handleSubmit,
			onClose: this.onClose,
			title: drawerTitle
		};

		//序号旁的checkbox部分
		const rowSelection = {
			selectedRowKeys: selectedKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				// console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
				this.setState({
					selectedData: selectedRows,
					selectedKeys: selectedRowKeys
				});
			},
			getCheckboxProps: record => ({
				disabled: record.name === 'Disabled User', // Column configuration not to be checked
				name: record.name
			})
		};
		function onChange(e) {
			console.log(`checked = ${e.target.checked}`);
		}
		const { getFieldDecorator}=this.props.form
		return (
			<div className="shadow-radius">
				{/* <Card>
					<BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
				</Card> */}

				<Tabs
					tabBarExtraContent={
						<div className="buttonList">
							<Button icon="plus" onClick={() => this.handleModal(0, {})} type="primary">
								{' '}
								添加
							</Button>
							{/* 修改数据 新增和修改中的数据都比显示的数据多几项 */}
							<Button icon="eye" onClick={() => this.handleModal(1, {})} type="primary">
								修改
							</Button>
							<BasicConfirm title="确认删除?" api={1} icon="delete" button={true} buttonName="删除" data={selectedData} handleConfirm={this.handleConfirm} />
						</div>
					}
				>
					<TabPane tab="班组" key="1">
						<Table columns={columns} rowSelection={rowSelection} rowKey={(record, index) => index} dataSource={dataSource} pagination={false} loading={loading} />
						<Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} />
					</TabPane>
				</Tabs>

				<BasicDrawer {...drawerProps} />

				<Modal
				title="绑定班组人员"
				visible={this.state.visibleDispatch}
				onOk={this.handleOk}
				onCancel={this.handleCancel}
				okText="确认"
				cancelText="取消"
				>
					<div>
					<Form>
						<Form.Item>
							{getFieldDecorator('chooseDataUser')(
								<Select
								mode="multiple"
								style={{ width: '100%' }}
								placeholder="请选择人员"
								onChange={this.onChangeModal}
								// defaultValue={this.state.defaultUser}
							>
									{userList && userList.map(item=>{
										return <Option key={item.userId}>{item.userName}</Option>
									})}
								</Select>
							)}
						</Form.Item>
					</Form>
					</div>
				</Modal>
			</div>
		);
	}
}
export default Form.create()(TeamGroups);
